import React, { Component } from 'react';
import { StyleSheet, View, Image, TouchableOpacity, Text, ImageBackground } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';

import {
  isAndroid,
  mainBgColorWhite,
  px2dp,
  screenWidth,
} from '../../../common/styles';
import Video from 'react-native-video';
import { iconPlay, iconVideo } from '../../../image';
import api from '../../../api';

export default class MainVideoPlay extends Component {
  constructor(props) {
    super(props);
    this.state = {
      paused: true, //视频暂停

      duration: '', //播放时间
      currentTime: '', //当前时间
      contentTitle: '', //标题
      contentUrl: '', //视频地址
      imageId: '', //海报页
    };
  }

  componentDidMount() {
    // api.home.getTextProtol({ code: 'wlVideoLink' }).then((res) => {
    //   if (res.success) {
    //     const { contentTitle, contentUrl, imageId } = res.data;
    //     this.setState({ contentTitle, contentUrl, imageId });
    //   } else {
    //     this.setState({ noTip: '暂无内容' });
    //   }
    // });
  }
  checkUrlWithString = (str_url) =>{
    var strRegex = "((https|http|ftp|rtsp|mms)?://)"
        + "(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
        + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
        + "|" // 允许IP和DOMAIN（域名）
        + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
        + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
        + "[a-z]{2,6})" // first level domain- .com or .museum
        + "(:[0-9]{1,4})?" // 端口- :80
        + "((/?)|" // a slash isn't required if there is no file name
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)";
    var re = new RegExp(strRegex);
    if (re.test(str_url)){
        return true
    } else {
        return false
    }
}

  render() {
    const { paused, duration, imageId, currentTime } = this.state;     
    const {contentUrl, introducePic, contentTitle} = this.props;
    return (
      <TouchableOpacity
        style={styles.videoWrap}
        activeOpacity={0.8}
        onPress={() => {
          this.onChange('paused', !paused);
          //   if (parseInt(currentTime) === parseInt(duration)) {
          //     this.player.seek(0);
          //   }
        }}>
        {this.checkUrlWithString(contentUrl) ?
          <Video
            ref={(ref) => {
              this.player = ref;
            }}
            source={{ uri: contentUrl }}
            poster={!!introducePic ? introducePic : ''}
            paused={paused}
            onProgress={(e) => this.customerOnprogress(e)}
            onLoad={(e) => this.customerOnload(e)}
            onEnd={() => {
              this.onChange('paused', true);
            }}
            repeat={isAndroid ? false : true}
            resizeMode="cover"
            posterResizeMode="cover"
            style={styles.video}
          />
        : null}

        {paused && (
          <ImageBackground
            style={styles.postWrap}
            imageStyle={{ borderRadius: px2dp(12) }}
            source={!currentTime ? { uri: !!introducePic ? introducePic : '' } : { uri: '' }}
            >
            <Image
              source={iconPlay}
              style={styles.playImg}
              resizeMode="cover"
            />
            <LinearGradient
              style={[styles.postDesc]}
              stystart={{ x: 0.5, y: 0 }}
              end={{ x: 0.5, y: 1 }}
              colors={['rgba(0,0,0,0)', 'rgba(0,0,0,0.6)']}>
              <View style={styles.postDesc}>
                <>
                  <Image
                    source={iconVideo}
                    style={styles.videoImg}
                    resizeMode="cover"
                  />
                  <Text style={styles.videoTitle}>{!!contentTitle?contentTitle:''}</Text>
                </>
                <View style={styles.videoTimeWrap}>
                  <Text style={styles.videoTime}>
                    {this.formatMediaTime(duration)}
                  </Text>
                </View>
              </View>
            </LinearGradient>
          </ImageBackground>
        )}
      </TouchableOpacity>
    );
  }

  onChange = (key, val) => {
    this.setState({ [key]: val });
  };

  //加载视频调用，主要是拿到 “总时间”，并格式化
  customerOnload = (e) => {
    let time = e.duration;
    this.setState({
      duration: time,
    });
  };

  // 获得当前的，播放时间数，但这个数是0.104，需要处理
  customerOnprogress = (e) => {
    let time = e.currentTime; // 获取播放视频的秒数
    this.setState({
      currentTime: time,
    });
  };
  //格式化音乐播放的时间为0：00。借助onProgress的定时器调用，更新当前时间
  formatMediaTime = (time) => {
    let minute = Math.floor(time / 60);
    let second = parseInt(time - minute * 60);
    minute = minute >= 10 ? minute : '0' + minute;
    second = second >= 10 ? second : '0' + second;
    return minute + ':' + second;
  };
}
const styles = StyleSheet.create({
  videoWrap: {
    width: screenWidth,
    height: px2dp(385),
    paddingHorizontal: px2dp(32),
    marginVertical: px2dp(32),
    borderRadius: px2dp(12),
    overflow: 'hidden',
    position: 'relative',
  },
  video: {
    height: '100%',
    borderRadius: px2dp(12),
  },
  postWrap: {
    height: '100%',
    width: '100%',
    position: 'absolute',
    left: px2dp(32),
    justifyContent: 'center',
    alignItems: 'center',
  },

  playImg: {
    width: px2dp(88),
    height: px2dp(88),
  },
  videoImg: {
    width: px2dp(32),
    height: px2dp(32),
  },
  postDesc: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    width: '100%',
    height: px2dp(80),
    position: 'absolute',
    bottom: 0,
    paddingHorizontal: px2dp(24),
    borderRadius: px2dp(12)
  },
  videoTitle: {
    flex: 1,
    color: mainBgColorWhite,
    marginLeft: px2dp(16),
  },
  videoTimeWrap: {
    // width: px2dp(75),
    height: px2dp(38),
    backgroundColor: '#000',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: px2dp(4),
    opacity: 0.5,
    paddingHorizontal: px2dp(10),
  },
  videoTime: {
    color: mainBgColorWhite,
  },
});
